interface Callback {
    (result: number): void;
}

class WebSocketClient {
    socket: WebSocket | undefined;
    userId: string = '';
    token: string = '';
    listeners: Array<Callback> | undefined;
    timer: any;

    constructor(userId: string, token: string) {
        this.userId = userId;
        this.token = token;
        this.listeners = [];
    }

    connect(host: string) {
        this.socket = new WebSocket(`${host}/deviceLink?linkType=aliDbayData&eventType=qryFocus&token=${this.token}`)
        console.log(this.socket.url)
        this.initEventListeners();
    }

    initEventListeners() {
        this.socket!.onopen = () => {
            console.log(new Date().getTime(), 'qry：WebSocket连接已打开')
            this.timer = setInterval(() => {
                this.socket!.send(JSON.stringify({}))
            }, 1000)
        }
        this.socket!.onclose = () => {
            console.log(new Date().getTime(), 'qry：WebSocket连接已关闭')
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }
        }
        this.socket!.onerror = (error) => {
            console.error('qry：WebSocket发生错误', error)
            if (this.timer) {
                clearInterval(this.timer);
                this.timer = null;
            }
        }
        this.socket!.onmessage = (event) => {
            console.log('qry：WebSocket收到', event.data)
            const value = parseInt(JSON.parse(event.data).focus);
            this.listeners?.forEach(e => e(value))
        }
    }

    setListener(func: Callback) {
        this.listeners?.push(func)
    }

    close() {
        this.socket?.close();
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }
}

export default WebSocketClient;